package com.gupao.rpc;

import com.gupao.rpc.annotation.RpcAnnotation;
import com.gupao.rpc.zk.IRegistryCenter;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcServer {

    private String serviceAddress;

    private IRegistryCenter registryCenter;

    private Map<String,Object> handerMap = new HashMap<>();

    public static final ExecutorService executorService = Executors.newCachedThreadPool();

    public RpcServer(String serviceAddress, IRegistryCenter registryCenter) {
        this.serviceAddress = serviceAddress;
        this.registryCenter = registryCenter;
    }

    /**
     * 绑定服务类全名和服务对象
     * @param services
     */
    public void bind(Object... services){
        for (Object service : services){
            RpcAnnotation rpcAnnotation = service.getClass().getAnnotation(RpcAnnotation.class);
            Class<?> clazz = rpcAnnotation.value();
            String version = rpcAnnotation.version();
            String serviceName = clazz.getName();
            if(version!=null && !version.equals("")){
                serviceName+=version;
            }
            handerMap.put(serviceName,service);
        }
    }

    public void publisher(){
        ServerSocket serverSocket = null;
        try {
            String[] address = serviceAddress.split(":");
            serverSocket = new ServerSocket(Integer.valueOf(address[1]));

            for (String s : handerMap.keySet()) {
                registryCenter.register(s,serviceAddress);
                System.out.println("已注册服务--->"+s+"-->"+address);
            }

            while (true){
                Socket socket = serverSocket.accept();
                executorService.execute(new ProcessorHander(socket,handerMap));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
